//
//  TKmainDetailHeaderView.m
//  Ticket
//
//  Created by 小禹宝宝 on 2017/10/24.
//  Copyright © 2017年 cy55. All rights reserved.
//
#import "TKSellerInformationViewController.h"
#import "TKmainDetailHeaderView.h"
#import "SDCycleScrollView.h"
#import "TKBidSheetView.h"
#import "NSString+JCKit.h"
#import "TKMyOrderViewController.h"

@interface TKmainDetailHeaderView ()<SDCycleScrollViewDelegate,UITextFieldDelegate
>
@property (weak, nonatomic) IBOutlet SDCycleScrollView *carouselView;//SDCycleScrollView

@property (weak, nonatomic) IBOutlet UIButton *iconBtn;
@property (weak, nonatomic) IBOutlet UILabel *countdownLabel;
@property (weak, nonatomic) IBOutlet UIButton *bidBtn;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *priceLabel;
@property (weak, nonatomic) IBOutlet UILabel *depositLabel;
@property (weak, nonatomic) IBOutlet UIImageView *depositImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *updateBtn;
@property (weak, nonatomic) IBOutlet UIButton *minusBtn;
@property (weak, nonatomic) IBOutlet UIButton *addBtn;
@property (weak, nonatomic) IBOutlet UITextField *leftNumberTextField;

@property (nonatomic, strong) UIView *lineView;
//@property (nonatomic,strong)SDCycleScrollView * topScrollView;
@property (nonatomic,strong) dispatch_source_t timer;
@property (nonatomic, strong) TKBidSheetView *bidSheetView;
@property (nonatomic, copy) NSString *countDownStr;

@end
@implementation TKmainDetailHeaderView

-(void)awakeFromNib {
    [super awakeFromNib];
    [self addLineView];
    self.titleLabel.textColor = [BLColorConfig textColor];
    self.nameLabel.textColor = [BLColorConfig textColor];
    self.countdownLabel.textColor = [BLColorConfig mainColor];
    self.priceLabel.textColor = [BLColorConfig textColor];
    self.depositLabel.textColor = [BLColorConfig textColor];
    self.bidBtn.backgroundColor = [BLColorConfig mainColor];
    [self.bidBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.iconBtn.layer.borderWidth = 2.0f;
    self.iconBtn.layer.borderColor = [[UIColor jc_colorWithHexString:@"eeeeee"] CGColor];
    self.iconBtn.layer.cornerRadius = self.iconBtn.bounds.size.width/2;
    self.iconBtn.layer.masksToBounds = YES;
    self.iconBtn.contentMode = UIViewContentModeScaleAspectFill;
    self.minusBtn.backgroundColor = [BLColorConfig mainColor];
//    [self.minusBtn setTitleColor:[BLColorConfig mainColor] forState:UIControlStateNormal];
    self.addBtn.backgroundColor = [BLColorConfig mainColor];
//    [self.addBtn setTitleColor:[BLColorConfig mainColor] forState:UIControlStateNormal];
    self.leftNumberTextField.delegate = self;
    self.leftNumberTextField.text = @"1";

    [self configCarouselView];

}

- (void)configCarouselView {
    self.carouselView.autoScrollTimeInterval = 3;
    self.carouselView.showPageControl = YES;
    self.carouselView.delegate = self;
    


}


- (void)addLineView
{
    _lineView = [[UIView alloc] init];
    _lineView.backgroundColor = [BLColorConfig lineColor];
    [self addSubview:_lineView];
    CGFloat height = 1.f/[UIScreen mainScreen].scale;
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(height);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(-height);
    }];
}



#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    DDLogInfo(@"%ld被点击了",(long)index);
//    CHLCallinItemModel *item = _callinListResultModel.items[index];
//    if ([item._link_url length] == 0) {
//        return;
//    }
//    
//    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:item._link_url]];
}

- (void)setModel:(TKGoodsInfo *)model {
    _model = model;
    
    NSMutableArray *picts = @[].mutableCopy;
    [model.pictures enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *url = obj[@"url"];
        [picts addObject:url];
    }];
    DDLogInfo(@"%@",picts);
    self.carouselView.imageURLStringsGroup =picts;
//    self.leftNumberTextField.text = model.left_number;
    self.titleLabel.text = model.title;
    self.nameLabel.text = model.user.user_name;
    [self.iconBtn sd_setImageWithURL:[NSURL URLWithString:model.user.user_portrait] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"icon_placeholder"]];
    self.depositLabel.text = [NSString stringWithFormat:@"¥ %@",model.deposit];
    [self refreshDataForCountDown:model.left_seconds];
    if (model.sell_type == 1) {
        self.countdownLabel.hidden = YES;
        self.updateBtn.hidden = YES;
        self.priceLabel.text = [NSString stringWithFormat:@"¥ %@",model.price];
        [self.bidBtn setTitle:@"购买" forState:UIControlStateNormal];
    } else {
        self.countdownLabel.hidden = NO;
        self.updateBtn.hidden = NO;
        self.leftNumberTextField.hidden = YES;
        self.addBtn.hidden = YES;
        self.minusBtn.hidden = YES;
        if ([model.top_price jc_isValidString]) {
            self.priceLabel.text = [NSString stringWithFormat:@"¥ %@",model.top_price];
        } else {
            self.priceLabel.text = [NSString stringWithFormat:@"¥ %@",@"0.00"];
        }
        [self.bidBtn setTitle:@"出价" forState:UIControlStateNormal];
    }

}
#pragma mark - Action
- (IBAction)iconAction:(id)sender {
    //跳转到店家个人主页
    TKSellerInformationViewController *vc = [TKSellerInformationViewController new];
    vc.user = self.model.user;
    [KSNavi push:vc];
}
- (IBAction)bidAction:(id)sender {
    [self endEditing:YES];
    if ([self.countDownStr isEqualToString:@"0"]) {
        [self ks_showToast:@"亲，该商品已截拍，再看看其他的吧"];
        return;
    }
    if ( _model.sell_type == 1 ) {
        //一口价
        NSDictionary *params = @{@"goods_id":self.model.id,@"number":self.leftNumberTextField.text,@"price":self.model.price};
        @weakify(self)
        [BLApi POST:URL_Order_add parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
            @strongify(self)
            BLBaseResponse *resp = responseObject;
            if ([resp isSuccess]) {
                NSDictionary *info = resp.info;
                NSString *order_id = info[@"order_id"];
                DDLogInfo(@"%@",order_id);
                //TO DO: 1.服务器加签 和 调用支付宝
                //2.支付成功后跳转到订单列表
                TKMyOrderViewController *orderVC = [TKMyOrderViewController new];
                orderVC.buy_user_id = [TKAccountManager sharedManager].accountInfo.result.info.user_id;
                [KSNavi push:orderVC];
                
            }
        }];

        
    } else {
        //拍卖 跳转
        NSDictionary *params = @{@"goods_id":self.model.id};
        @weakify(self)
        [BLApi GET:URL_Goods_get_topPrice parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
            @strongify(self)
            BLBaseResponse *resp = responseObject;
            if ([resp isSuccess]) {
                NSDictionary *info = resp.info;
                NSString *top_price = info[@"top_price"];
                DDLogInfo(@"%@",top_price);
                if ([top_price jc_isValidString]) {
                    self.bidSheetView.top_price = top_price;
                    if ([top_price floatValue] > 0) {
                        float p = [top_price floatValue] + [self.model.step_price floatValue];
                        self.bidSheetView.bid_price = [NSString stringWithFormat:@"%.2f",p];
                    } else {
                        self.bidSheetView.bid_price = self.model.min_price;
                    }
                } else {
                    if ([self.model.top_price jc_isValidString]) {
                        self.bidSheetView.top_price = self.model.top_price;
                    }
                }
                @weakify(self)
                [self.bidSheetView bidClicked:^(id price) {
                    @strongify(self)
                    //拿到出价值price
                    NSString *curprice = price;
                    if ([curprice floatValue] < [self.bidSheetView.bid_price floatValue]) {
                        [self ks_showToast:@"出价必须高于领先价哦"];
                        return ;
                    }
                    //调用购买订单接口
                    //暂时价格写死0.01
//                    curprice = @"0.01";
                    NSDictionary *params = @{@"goods_id":self.model.id,@"number":@"0",@"price":curprice};
                    @weakify(self)
                    [BLApi POST:URL_Order_add parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
                        @strongify(self)
                        BLBaseResponse *resp = responseObject;
                        if ([resp isSuccess]) {
                            NSDictionary *info = resp.info;
                            NSString *order_id = info[@"order_id"];
                            DDLogInfo(@"%@",order_id);
                            //TO DO: 1.服务器加签 和 调用支付宝
                            //2.支付成功后跳转到订单列表
                            TKMyOrderViewController *orderVC = [TKMyOrderViewController new];
                            orderVC.buy_user_id = [TKAccountManager sharedManager].accountInfo.result.info.user_id;
                            [KSNavi push:orderVC];

                        }
                    }];
                    
                }];
                [self.bidSheetView show];
                }
        }];

    }

}
- (IBAction)updateAction:(id)sender {
    //更新最高价格
    NSDictionary *params = @{@"goods_id":self.model.id};
    @weakify(self)
    [BLApi GET:URL_Goods_get_topPrice parameters:params decodeClass:[BLBaseResponse class] completion:^(id responseObject, id responseDataOriginal, NSError *error) {
        @strongify(self)
        BLBaseResponse *resp = responseObject;
        if ([resp isSuccess]) {
            NSDictionary *info = resp.info;
            NSString *top_price = info[@"top_price"];
            DDLogInfo(@"%@",top_price);
            if ([top_price jc_isValidString]) {
                self.priceLabel.text = [NSString stringWithFormat:@"¥ %@",top_price];
            }
        }
    }];
}

- (IBAction)minusAction:(id)sender {
    if ([self.leftNumberTextField.text intValue] > 0) {
        self.leftNumberTextField.text =[NSString stringWithFormat:@"%d",[self.leftNumberTextField.text intValue]-1];
    }
}

- (IBAction)addAction:(id)sender {
    self.leftNumberTextField.text =[NSString stringWithFormat:@"%d",[self.leftNumberTextField.text intValue]+1];
}


- (void)refreshDataForCountDown:(int64_t )seconds{
    if (!self.timer) {
        __block int64_t second = seconds;
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
        dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1.0f * NSEC_PER_SEC, 0.0f * NSEC_PER_SEC);
        dispatch_source_set_event_handler(self.timer, ^{
            
            @autoreleasepool {
                if (second > 0) {
                    second--;
                    self.countDownStr = [NSDate cy_timeStringWithSeconds:second];
                    self.countdownLabel.text = [NSString stringWithFormat:@"距离结束：%@",self.countDownStr];
                } else {
                    self.countDownStr = @"0";
                    self.countdownLabel.text = @"该商品已截拍";
                }

            }
        });
        dispatch_resume(self.timer);
    }
}

- (TKBidSheetView *)bidSheetView {
    if (!_bidSheetView) {
        _bidSheetView = [[TKBidSheetView alloc] init];
    }
    return _bidSheetView;
}

#pragma mark - UITextFieldDelegate
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    NSLog(@"textfield text %@",textField.text);

    return YES;
}
@end
